package com.atlin.project.utils;

import com.atlin.project.common.ErrorCode;
import com.atlin.project.contant.FileConstant;
import com.atlin.project.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;


/**
 * 文件本地存储
 */
@Slf4j
public class LocalFileUtil {


    /**
     * 本地文件存储
     *
     * @param file       文件
     * @param fileName   文件名称
     * @param bucketName 存储目录
     */
    public static void save(File file, String fileName, String bucketName) {
        try {
            // fileName为空，说明要使用源文件名上传
            if (fileName == null) {
                fileName = RandomStringUtils.randomAlphanumeric(8) + System.currentTimeMillis();
                fileName = fileName.replaceAll(" ", "_");
            }
            File target = new File(bucketName);
            if (!target.exists() || !target.isDirectory()) {
                target.mkdirs();
            }

            Files.copy(file.toPath(), new File(bucketName + fileName).toPath());
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件存储失败");
        }
    }

    /**
     * 文件获取
     *
     * @param fileName   文件名称
     * @param bucketName 目录
     * @param response   响应
     */
    public static void previewFile(String fileName, String bucketName, HttpServletResponse response) {
        byte[] fileByte = null;
        try (ServletOutputStream os = response.getOutputStream()) {
            File file = new File(bucketName + fileName);

            if (!file.exists()) {
                log.error("文件:[{}] 不存在", bucketName + fileName);
                throw new BusinessException(ErrorCode.NULL_ERROR, "文件不存在");
            }

            fileByte = Files.readAllBytes(file.toPath());
            os.write(fileByte);

        } catch (IOException e) {
            log.error("文件：{}读取失败", bucketName + fileName);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片读取失败");
        }
    }

    /**
     * 获取Base64编码后的图片文件
     *
     * @param fileName
     * @param bucketName
     * @return
     */
    public static String getImgFileTRBase64(String fileName, String bucketName) {
        byte[] fileByte = null;

        try {
            File file = new File(bucketName + fileName);
            if (!file.exists()) {
                log.error("文件:[{}] 不存在", bucketName + fileName);
                throw new BusinessException(ErrorCode.NULL_ERROR, "文件不存在");
            }
            fileByte = Files.readAllBytes(file.toPath());
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片读取失败");
        }

        return "data:image/png;base64," + Base64.encodeBase64String(fileByte);
    }
    
}
